﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace FlashPay.DAO.Impl
{
    using FlashPay.DAO.Interface;

    using FlashPay.EF;

    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.EF.Models;

    /// <summary>
    /// 用户角色数据接口实现
    /// </summary>
    public class UserRoleDaoImpl : IDisposable, UserRoleDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public UserRoleDaoImpl(FlashPayContext context)
        {
            _context = context;
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取用户角色
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>UserInfo</returns>
        public UserRole Get(int id)
        {
            return _context.UserRole.Where(x => x.UrId == id).FirstOrDefault();
        }

        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <returns>List<UserRole></returns>
        public List<UserRole> GetByUserIds(List<int> ids)
        {
            return _context.UserRole.Where(x => ids.Contains(x.UrUid)).ToList();
        }


        /// <summary>
        /// 删除用户角色
        /// </summary>
        /// <param name="menuId">用户编号</param>
        /// <returns></returns>
        public bool DeleteByUserId(int userId, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            var result = false;

            var userRoleList = _flashPayContext.UserRole.Where(p => p.UrUid.Equals(userId)).ToList();
            if (userRoleList.Count <= 0)
            {
                result = true;
            }
            else
            {
                userRoleList.ForEach(item => {
                    _flashPayContext.UserRole.Remove(item);
                    if (_flashPayContext.SaveChanges() > 0)
                    {
                        result = true;
                    }
                });
            }
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public JResult<UserRole> Add(UserRole model, FlashPayContext flashPayContext = null)
        {
            var result = new JResult<UserRole>()
            {
                Success = false
            };

            try
            {
                var _flashPayContext = (flashPayContext ?? _context);

                _flashPayContext.UserRole.Add(model);
                _flashPayContext.SaveChanges();

                result.Success = true;
                result.Data = model;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 根据角色编号获取用户角色数据
        /// </summary>
        /// <param name="roleId">角色编号</param>
        public List<UserRole> GetByRoleId(int roleId) {
            return _context.UserRole.Where(x => x.UrRid == roleId).ToList();
        }

        //根据用户ID获取角色信息
        public PagedList<UserRole> GetRoleByUID(int uID)
        {
            PagedList<UserRole> result = new PagedList<UserRole>();

            try
            {
                var UserRole = from ur in _context.UserRole
                           join sy in _context.SysRole on ur.UrRid equals sy.RId
                           join ui in _context.UserInfo on ur.UrUid equals ui.UId
                           orderby ur.UrId descending
                           where ur.UrUid == uID && sy.RStatus == (int)Entity.Enum.RoleStatus.显示

                           select new UserRole
                           {
                               UrId = ur.UrId,
                               UrUid = ur.UrUid,
                               UrRid = ur.UrRid,
                               CreateDate = ur.CreateDate,
                               UrR = sy,
                               UrU = ui
                           };

                List<UserRole> list = UserRole.ToList();
                result.TotalCount = list.Count();
                result.TData = list;
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = "服务器异常:" + ex.Message;
            }
            return result;
        }

        //获取用户角色值
        public ICollection<UserRole> GetUserRoleList(int uID)
        {
            var first = _context.UserRole.Where(u => u.UrUid == uID);
            if (first.FirstOrDefault() == null) return null;
            return first.ToList();
        }

        //更新用户角色
        public int UpdateUserRole(UserInfoQuery query)
        {
            //如果角色值等于空，先删除再插入
            var role = _context.UserRole.Where(e => e.UrUid == query.Id);
            if (role.FirstOrDefault() != null)
            {
                var list = role.ToList();
                for (int i = 0; i < list.Count; i++)
                {
                    _context.UserRole.Remove(list[i]);
                }
                _context.SaveChanges();
            }

            if (query.userRole != null)
            {
                for (var i = 0; i < query.userRole.Count; i++)
                {
                    UserRole ur = new UserRole();
                    ur.UrUid = query.Id.Value;
                    ur.UrRid = Convert.ToInt32(query.userRole[i]);
                    ur.CreateDate = DateTime.Now;
                    _context.UserRole.Add(ur);
                }
            }
            return _context.SaveChanges();
        }

        /// <summary>
        /// 删除URId等于roleId
        /// </summary>
        /// <param name="menuId">角色编号</param>
        /// <returns></returns>
        public bool DeleteByroleRId(int roleRId)
        {
            var result = false;

            try
            {
                var menuList = _context.UserRole.Where(p => p.UrRid.Equals(roleRId)).ToList();
                menuList.ForEach(item => {
                    _context.UserRole.Remove(item);
                    if (_context.SaveChanges() <=0 )
                    {
                        throw new Exception("删除角色失败");
                    }
                });
                result = true;
            }
            catch (Exception ex) {
                result = false;
            }
            return result;
        }
    }
}
